package at.fhj.petsitter.authentication;

import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.Produces;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.TypedQuery;

import at.fhj.petsitter.model.User;

@SessionScoped
@Named
public class Login implements Serializable {

	private static final long serialVersionUID = 7965455427888195913L;

	@Inject
	private Credentials credentials;

	private User currentUser;

	@PersistenceContext(type = PersistenceContextType.EXTENDED)
	private EntityManager entityManager;

	public void login() throws Exception {
		try {
			Object obj = this.entityManager
					.createQuery(
							"SELECT u FROM User u WHERE u.email LIKE :email AND u.password LIKE :password")
					.setParameter("email", credentials.getEmail())
					.setParameter("password", credentials.getPassword())
					.getSingleResult();
			User user = (User) obj;
			if (user != null) {
				this.currentUser = user;
				FacesContext.getCurrentInstance().addMessage(
						null,
						new FacesMessage("Welcome, "
								+ currentUser.getFirstName()));
			} else {
				displayWrongCredentialsMsg();
			}
		} catch (javax.persistence.NoResultException ex) {
			displayWrongCredentialsMsg();
		}
	}

	public void logout() {
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage("Goodbye, " + currentUser.getFirstName()));
		currentUser = null;
	}

	public boolean isLoggedIn() {
		return currentUser != null;
	}

	public void displayWrongCredentialsMsg() {
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage("Wrong credentials!"));
	}

	@Produces
	@LoggedIn
	public User getCurrentUser() {
		return currentUser;
	}

}